package com.yyk.dzvisit.vo;

import com.yyk.dzvisit.enums.RequestContextEnum;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * create by zhouc 2019/11/04
 */
public class RequestContext {

    private static final ThreadLocal<RequestContext> THREAD_LOCAL = new ThreadLocal<>();

    /**
     * 上下文内容
     */
    private Map<String, String> contextDetail = new HashMap<>();


    public static RequestContext getContext() {
        RequestContext requestContext = THREAD_LOCAL.get();
        if (requestContext == null) {
            requestContext = new RequestContext();
            THREAD_LOCAL.set(requestContext);
        }
        return requestContext;
    }

    /**
     * 关闭上下文
     */
    public static void clear() {
        THREAD_LOCAL.remove();
    }

    /**
     * 增加上下文内容
     */
    public void addContextDetail(String key, String value) {
        RequestContextEnum requestContextEnum = RequestContextEnum.getByName(key);
        // 如果key为token
        if (requestContextEnum != null && requestContextEnum.equals(RequestContextEnum.TOKEN)) {
            if (StringUtils.isNotBlank(value) && StringUtils.isNotEmpty(value)
                    && StringUtils.split(value, ".").length != 3) {
                return;
            }
        }
        contextDetail.put(key, value);
    }

    /**
     * 删除上下问内容
     */
    public void removeContextDetail(String key) {
        contextDetail.remove(key);
    }

    /**
     * 获取上下文内容
     */
    public String getContextDetail(String key) {
        return contextDetail.get(key);
    }

    public Map<String, String> getContextDetails() {
        return contextDetail;
    }
}
